package com.base

import android.content.Context
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<DATA, VH : RecyclerView.ViewHolder?> : RecyclerView.Adapter<VH> {
    var mContext: Context
    var dataList = arrayListOf<DATA>()
    var onItemClickListener: OnItemClickListener<DATA>? = null

    constructor(context: Context) {
        mContext = context
    }

    constructor(context: Context, listener: OnItemClickListener<DATA>?) {
        mContext = context
        onItemClickListener = listener
    }

    open fun setData(data: DATA) {
        if (data != null) {
            dataList.clear()
            dataList.add(data)
            notifyDataSetChanged()
        }
    }

    open fun setData(dataList: ArrayList<DATA>?) {
        this.dataList.clear()
        dataList?.let {
            this.dataList.addAll(dataList)
        }
        notifyDataSetChanged()
    }

    fun addData(data: DATA?) {
        data?.let {
            dataList.add(data)
            notifyItemChanged(dataList.size - 1)
        }
    }

    fun removeData(position: Int) {
        dataList?.let {
            it.removeAt(position)
            notifyDataSetChanged()
        }
    }

    fun addData(dataList: ArrayList<DATA>?) {
        if (dataList != null && dataList.size > 0) {
            var sizeOld = 0
            if (this.dataList.size > 0) {
                sizeOld = this.dataList.size - 1
            }
            this.dataList.addAll(dataList)
            notifyItemChanged(this.dataList.size - 1)
        }
    }

    override fun onBindViewHolder(holder: VH & Any, position: Int) {
        onItemClickListener?.let { listener ->
            holder?.let { h ->
                h.itemView.setOnClickListener {
                    listener.onItemClick(
                        position,
                        getItem(position)
                    )
                }
            }

        }
        onBindView(holder, position, getItem(position))
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    open fun getItem(position: Int): DATA? {
        return if (position >= dataList.size) {
            null
        } else {
            dataList[position]
        }
    }

    protected abstract fun onBindView(holder: VH, position: Int, data: DATA?)
    open interface OnItemClickListener<DATA> {
        fun onItemClick(position: Int, data: DATA?)
    }
}